package com.atguigu.ssyx.acl.controller;

import com.atguigu.ssyx.acl.service.PermissionService;
import com.atguigu.ssyx.acl.service.RolePermissionService;
import com.atguigu.ssyx.common.result.Result;
import com.atguigu.ssyx.model.acl.Permission;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 杨林
 * @create 2023-07-07 11:01 星期五
 * description:
 */
@RequestMapping("/admin/acl/permission")
@CrossOrigin   //跨域
@RestController
@Api(tags = "权限管理")
public class PermissionController {

    @Autowired
    private PermissionService permissionService;

    @Autowired
    private RolePermissionService rolePermissionService;

    @ApiOperation(value = "获取所有菜单")
    @GetMapping
    public Result index(){
        List<Permission> list = permissionService.getAllMenu();
        return Result.ok(list);
    }


    //添加菜单
    @ApiOperation(value = "添加菜单")
    @PostMapping("/save")
    public Result save(@RequestBody Permission permission){
        permissionService.save(permission);
        return Result.ok();
    }

    //修改菜单
    @ApiOperation(value = "修改菜单")
    @PutMapping("/update")
    public Result update(@RequestBody Permission permission){
        permissionService.updateById(permission);
        return Result.ok();
    }

    //删除菜单：如果当前菜单有自己菜单，需要递归删除
    @ApiOperation(value = "递归删除菜单")
    @DeleteMapping("/remove/{id}")
    public Result delete(@PathVariable Long id){
        //方案1：将要删除的菜单及其子菜单递归删除
        permissionService.removeChainById(id);
        return Result.ok();
        //方案2：如果要删除的菜单下有子菜单，要求其先删除子菜单在删除当前菜单：前端已经实现控制

    }


    /**
     * 查看某个角色已分配的权限
     * @return
     */
    @ApiOperation(value = "查看某个角色已分配的权限")
    @GetMapping("/toAssign/{roleId}")
    public Result toAssign(@PathVariable("roleId") Long roleId){
        List<Permission> result = rolePermissionService.toAssign(roleId);
        return Result.ok(result);
    }

    /**
     * 给角色授权
     * @return
     */
    @ApiOperation(value = "给角色授权")
    @PostMapping("/doAssign")
    public Result doAssign(@RequestParam("roleId") Long roleId,
                           @RequestParam("permissionId") List<Long> permissionIds){
        rolePermissionService.doAssign(roleId,permissionIds);
        return Result.ok();
    }
}
